package com.tiantian.app.activities;

 
 
import org.json.JSONObject;

import com.infindo.frame.data.mo.MoliscMessage;
import com.infindo.frame.data.mo.ServiceConstant;
import com.infindo.frame.util.EnumConstant.MessageCode;
import com.tiantian.app.R;
import com.tiantian.app.data.mo.LoginObj;
import com.tiantian.app.data.mo.LoginResultTeacher;
import com.tiantian.app.manager.DataModel;
import com.tiantian.app.manager.HttpManager;
import com.tiantian.app.manager.SharedPreferenceSetting;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
 
import android.util.Log;
import android.view.View;
 
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.infindo.frame.util.ScreenManager;
 
 /** 
 * @author  William.Chen
 * @version 创建时间：2013-3-9 上午10:43:29 
 * 类说明         登录界面
 */
public class PageLoginActivity extends SuperActivity {
	
	private final String TAG = PageLoginActivity.class.getSimpleName();
	
	private final int LOGIN_REQUEST_HANDLER = 10;
	private final int LOGIN_REQUEST_SUCCESS = 20;
	private final int LOGIN_USERNAME_NO_CORRECT_DIALOG = 30;
	private final int LOGIN_PASSWORD_NO_CORRECT_DIALOG = 40;
	
	private EditText etUsername, etPassword;
	private Button btnRememberPassword,btnAutoLogin,loginBtn,registerBtn,getPasswordBtn;
	
	
	/* 
	 * @see com.tiantian.app.activities.SuperActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_login);
		onResetUI();
	}

	/* 
	 * @see com.tiantian.app.activities.SuperActivity#callback(java.lang.String, int, java.lang.Object)
	 */
	@Override
	public void callback(String type, int position, Object obj) {
		// TODO Auto-generated method stub
		Log.e(TAG,"type: "+type+"   obj:"+obj);
		closeLoadingDialg();
		if("login".equals(type)){
			if(obj instanceof MoliscMessage){
				LoginResultTeacher lrTeacher = (LoginResultTeacher)obj;
				if(MessageCode.OK.toString().equals(lrTeacher.getResult())){
					SharedPreferenceSetting.setUserName(this, etUsername.getText().toString());
					SharedPreferenceSetting.setPassword(this, etPassword.getText().toString());
					Log.e(TAG,"LoginResultTeacher:"+lrTeacher.getLastAnnounce().getAddUser().getTrueName()+":"+lrTeacher.getClassName()+" : "+lrTeacher.getUserObj().getEmail());
				    DataModel.tempLoginResultTeacher = lrTeacher;
				     
				    handler.sendEmptyMessage(LOGIN_REQUEST_SUCCESS);

				}
			}
		}
	}
	
	/* 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/* 
	 * @see com.tiantian.app.activities.SuperActivity#findView()
	 */
	@Override
	public void findView() {
		// TODO Auto-generated method stub
		superTitle = (TextView)findViewById(R.id.superTitle);
		superTitle.setText("用户登录");
		
		etUsername = (EditText)findViewById(R.id.etUsername);
		etPassword = (EditText)findViewById(R.id.etPassword);
		
		btnRememberPassword = (Button)findViewById(R.id.btnRememberPassword);
		btnAutoLogin = (Button)findViewById(R.id.btnAutoLogin);
		loginBtn = (Button)findViewById(R.id.loginBtn);
		registerBtn = (Button)findViewById(R.id.registerBtn);
		getPasswordBtn = (Button)findViewById(R.id.getPasswordBtn);
	}

	/* 
	 * @see com.tiantian.app.activities.SuperActivity#initData()
	 */
	@Override
	public void initData() {
		// TODO Auto-generated method stub
		String userName = SharedPreferenceSetting.getUserName(this);
		String password = SharedPreferenceSetting.getPassword(this);
		
		etUsername.setText(""+userName);
		updateRememberAutoStatus();
		boolean bolRememberPassword = SharedPreferenceSetting.getRememberPassword(this);
		if(bolRememberPassword){
			   etPassword.setText(""+password);
 
		}
		boolean bolAutoLogin = SharedPreferenceSetting.getAutoLogin(this);
		if(bolAutoLogin && etUsername.getText().toString().length()>0 && etPassword.getText().toString().length()>0){
			   Drawable left = getResources().getDrawable(R.drawable.icon_choice_select);
			   btnAutoLogin.setCompoundDrawablesWithIntrinsicBounds(left, null,null, null);
			  new Thread() {
	 
				  public void run() {
					  try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					handler.sendEmptyMessage(LOGIN_REQUEST_HANDLER);
				  }; 
			   }.start();
		}
	}

	/* 
	 * @see com.tiantian.app.activities.SuperActivity#onResetUI()
	 */
	@Override
	public void onResetUI() {
		// TODO Auto-generated method stub
		findView();
		setListener();
		initData();
	}

	/* 
	 * @see com.tiantian.app.activities.SuperActivity#setListener()
	 */
	@Override
	public void setListener() {
		// TODO Auto-generated method stub
		btnRememberPassword.setOnClickListener(this);
		btnAutoLogin.setOnClickListener(this);
		loginBtn.setOnClickListener(this);
		registerBtn.setOnClickListener(this);
		getPasswordBtn.setOnClickListener(this);
		
	}
	
	final Handler handler = new Handler(){
		  public void handleMessage(Message msg) {
			  switch(msg.what){
			  case LOGIN_REQUEST_HANDLER:
				  Log.e("","=================================== ---- =====================================");
				  requestLogin();
				  break;
			  case LOGIN_REQUEST_SUCCESS:
				   Intent it = new Intent(PageLoginActivity.this,PageTeacherHomeActivity.class);
				   startActivity(it);
				   ScreenManager.getScreenManager().popActivity(PageLoginActivity.this);
				  
				  break;
			  }
		  };
	};
		
	
	/* 
	 * @see com.tiantian.app.activities.SuperActivity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
		case LOGIN_USERNAME_NO_CORRECT_DIALOG:
    		if(progressDialog!=null)
    			progressDialog.dismiss();
    		alertDialog = new AlertDialog.Builder(this)
	  		.setTitle("").setIcon(android.R.drawable.ic_dialog_info).setMessage("用户名输入不正确!")
            .setPositiveButton( "", new DialogInterface.OnClickListener()
            {
                public void onClick( DialogInterface dialog, int whichButton )
                {
                         
                }
                    
            } ).setNegativeButton("", new DialogInterface.OnClickListener()
            {
                public void onClick( DialogInterface dialog, int whichButton )
                {
 
                }
            } )
            .create();
			return alertDialog;
		case LOGIN_PASSWORD_NO_CORRECT_DIALOG:
    		if(progressDialog!=null)
    			progressDialog.dismiss();
    		alertDialog = new AlertDialog.Builder(this)
	  		.setTitle("").setIcon(android.R.drawable.ic_dialog_info).setMessage("密码输入不正确!")
            .setPositiveButton( "", new DialogInterface.OnClickListener()
            {
                public void onClick( DialogInterface dialog, int whichButton )
                {
                         
                }
                    
            } ).setNegativeButton("", new DialogInterface.OnClickListener()
            {
                public void onClick( DialogInterface dialog, int whichButton )
                {
 
                }
            } )
            .create();
			return alertDialog;
		}
		return super.onCreateDialog(id);
	}
	
	private void updateRememberAutoStatus(){
		Drawable left;
		boolean bolRememberPassword = SharedPreferenceSetting.getRememberPassword(this);
		if(bolRememberPassword){
   		     left = getResources().getDrawable(R.drawable.icon_choice_select);
		     btnRememberPassword.setCompoundDrawablesWithIntrinsicBounds(left, null,null, null);
		}else{
	   		 left = getResources().getDrawable(R.drawable.icon_choice_no_select);
			 btnRememberPassword.setCompoundDrawablesWithIntrinsicBounds(left, null,null, null);	 
		}
 
		boolean bolAutoLogin = SharedPreferenceSetting.getAutoLogin(this);
		if(bolAutoLogin){
	   		 left = getResources().getDrawable(R.drawable.icon_choice_select);
			 btnAutoLogin.setCompoundDrawablesWithIntrinsicBounds(left,null,null, null);
		}else{
    		 left = getResources().getDrawable(R.drawable.icon_choice_no_select);
    		 btnAutoLogin.setCompoundDrawablesWithIntrinsicBounds(left,null,null, null);
		}
	}

    /* 
     * @see com.tiantian.app.activities.SuperActivity#onClick(android.view.View)
     */
    @Override
    public void onClick(View view) {
    	// TODO Auto-generated method stub
    	super.onClick(view);
    	Intent it;
    	switch(view.getId()){
    	case R.id.btnRememberPassword:
    		boolean bolRememberPassword = SharedPreferenceSetting.getRememberPassword(this);
    		if(bolRememberPassword){
	    		 SharedPreferenceSetting.setRememberPassword(this, false);
    		}else{
	    		 SharedPreferenceSetting.setRememberPassword(this, true);
    		}
    		updateRememberAutoStatus();
    		break;
    	case R.id.btnAutoLogin:
    		boolean bolAutoLogin = SharedPreferenceSetting.getAutoLogin(this);
    		if(bolAutoLogin){
	    		 SharedPreferenceSetting.setAutoLogin(this, false);
    		}else{
	    		 SharedPreferenceSetting.setAutoLogin(this, true);
    		}
    		updateRememberAutoStatus();
    		break;
    	case R.id.loginBtn:
    		if(etUsername.getText().toString().length()<5){
    			showDialog(LOGIN_USERNAME_NO_CORRECT_DIALOG);
    			return;
    		}else if(etPassword.getText().toString().length()<6){
    			showDialog(LOGIN_PASSWORD_NO_CORRECT_DIALOG);
    			return;
    		}
    		requestLogin();
    		break;
    	case R.id.registerBtn:
    		it = new Intent(PageLoginActivity.this,PageChangePasswordActivity.class);
    		startActivity(it);
    		break;
    	case R.id.getPasswordBtn:
    		it = new Intent(PageLoginActivity.this,PageGetPasswordActivity.class);
    		startActivity(it);
    		break;
    	}
    }
    
    private void requestLogin(){
    	showDialog(LOADING_DIALOG);
    	LoginObj login = new LoginObj();
    	login.setUsername(""+etUsername.getText().toString());
    	login.setPassword(""+etPassword.getText().toString());
    	login.setAppId(""+DataModel.AppID);
    	login.setDeviceId(""+DataModel.DeviceID);
    	login.setLatitude("31.368881");
    	login.setLongitude("120.738372");
    	
    	HttpManager.requestPost(this, login, ServiceConstant.USER_LOGIN_TEACHER, "login", this);
    	
    }

 

}
